import subprocess
import logging
from urllib.parse import unquote_plus
from datetime import datetime
import requests
import pandas as pd
import re
from Determining_ad.test.test.test_generator_parquet import test_parquet_generator
from Determining_ad.test.test.test_revert_parquet import test_revert_parquet


def find_entity(stop_event):
    """
    记录logcat的方法
    :param stop_event: 事件
    :return:
    """
    # 启动adb logcat命令并将其输出定向到管道      标签为LOGCAT_CONSOLE且日志等级为INFO的日志
    # 判断是否为HUAWEI品牌
    brand = 'HUAWEI'
    adb_brand = subprocess.run(['adb', 'shell', 'getprop', 'ro.product.brand'], capture_output=True, text=True)
    phone_brand = adb_brand.stdout.strip()
    logging.info(f'手机厂商: {phone_brand}')
    result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
    output = result.stdout
    lines = output.split('\n')
    serial_number = None
    for line in lines:
        if '\tdevice' in line:
            serial_number = line.split('\t')[0]
    # logging.info(f'serial_number: {serial_number}')
    # 清除日志
    subprocess.Popen(['adb', '-s', serial_number, 'logcat', '-c'])

    if phone_brand == brand:
        logcat = subprocess.Popen(['adb', '-s', serial_number, 'logcat', '-s', 'jsLog'], stdout=subprocess.PIPE)
    else:
        logcat = subprocess.Popen(['adb', '-s', serial_number, 'logcat', '-s', 'LOGCAT_CONSOLE'], stdout=subprocess.PIPE)
    log_list = []
    while not stop_event.is_set():
        line = None
        # 从管道中读取一行输出
        try:
            line = logcat.stdout.readline().decode('utf-8')
        except KeyboardInterrupt:
            logging.info("用户中断了程序")

        # 如果没有更多的输出，则退出循环
        if not line:
            break
        # 如果line不为空，都是则把所有日志输出到一个log_df
        if line:
            if line not in log_list:
                log_list.append(line)

        # # 打印error
        # if "E/" in line:
        #     logging.error(line)

    # logging.info(f'log_list：{log_list}')
    logcat.terminate()  # 确保关闭adb logcat命令
    logcat.wait()  # 等待进程完全终止
    # get_log_dataframe(log_list)
    '''
    把所有日志都组成一个dataframe
    '''
    # 区分华为
    tem_list = []
    # logging.info(f'log_list: {log_list}')
    if phone_brand == brand:
        log_pattern = r'(\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\s+\d+\s+\d+\s+(\w)\s+jsLog\s*:\s*(.*)\r\n'

        for log_line in log_list:
            # logging.info(f'log_line: {log_line}')
            match = re.match(log_pattern, log_line)
            if match:
                timestamp, level, message = match.groups()
                tem_list.append([timestamp, level, message])
                # logging.info(f'匹配到的日志: {log_line}')
            # else:
            #     logging.warning(f'log_list没有匹配到的日志: {log_line}')
    else:
        log_pattern = r"(\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\s+\w+\s+\w+\s+(\w)\s+(LOGCAT_CONSOLE):\s+(.*?)\r\n"
        for log_line in log_list:
            match = re.match(log_pattern, log_line)
            if match:
                timestamp, level, _, message = match.groups()
                # logging.info(f'匹配到的日志: {log_line}')
                tem_list.append([timestamp, level, message])
    columns = [
        'Timestamp',
        'Level',
        'Message'
    ]
    df = pd.DataFrame(tem_list, columns=columns)
    # df = df.applymap(lambda x: 'Missing' if x.strip() == '' else x)
    df = df.replace(r'^\s*$', 'Missing', regex=True)
    # 把Timestamp字符串转换为datetime64[ns]类型
    current_year = str(datetime.now().year)
    df['Timestamp'] = df['Timestamp'].apply(lambda x: current_year + '-' + x)
    time_format = '%Y-%m-%d %H:%M:%S.%f'
    df['Timestamp'] = pd.to_datetime(df['Timestamp'], format=time_format)

    # 定义要查找的格式和关键字
    event_format = "===== 广告事件 ====="
    search_str = "解密后"
    # 筛选出符合特定格式的消息并组成 Series
    filtered_series = df.loc[df['Message'].str.contains(event_format, regex=False, na=False), 'Message']
    # 检查 Series 中是否有任何一行包含 "解密后" 字样
    match_found = filtered_series.str.contains(search_str, regex=False, na=False).any()
    if match_found:
        entity = 'hn'
    else:
        entity = 'bj'

        # 打印版本号
        result = df[df["Message"].str.contains(r"ver\s", na=False)]
        try:
            first_value = result["Message"].iloc[0]
            logging.info(f"版本号:{first_value}")
        except IndexError:
            logging.info("无版本号")

        # 打印oaid
        result = df[df["Message"].str.contains(r"oaid\s", na=False)]
        try:
            first_value = result["Message"].iloc[0]
            logging.info(f"{first_value}")
        except IndexError:
            logging.info("无oaid")
    # 保存all_df数据
    test_parquet_generator(df, entity)
    # 使用测试数据
    # entity, df = test_revert_parquet('Determining_ad/test/test/historical_data/data_bj_20250512_163814.parquet')
    return entity, df, phone_brand
